<?php
/**
 * @author css3 <css3@qq.com>
 */

namespace zonday\weixin\api;

/**
 * Class Qrcode
 */
class Qrcode extends Api
{
    const QR_SCENE = 'QR_SCENE';
    const QR_LIMIT_SCENE = 'QR_LIMIT_SCENE';
    const QR_LIMIT_STR_SCENE = 'QR_LIMIT_STR_SCENE';

    /**
     * 创建二维码
     * @see http://mp.weixin.qq.com/wiki/18/28fc21e7ed87bec960651f0ce873ef8a.html
     * @param mixed $expireSeconds 0或者false 为永久 单位秒
     * @param $actionName
     * @param $sceneId
     * @param string $sceneStr
     * @return mixed
     */
    public function create($expireSeconds, $actionName, $sceneId, $sceneStr = '')
    {
        if (!in_array($actionName, [self::QR_LIMIT_SCENE, self::QR_LIMIT_STR_SCENE, self::QR_SCENE])) {
            throw new \InvalidArgumentException('actionName 参数不正确');
        }

        $post = [
            'action_name' => $actionName,
            'action_info' => [
                'scene' => [
                    'scene_id' => $sceneId,
                    'scene_str' => $sceneStr
                ]
            ]
        ];

        if ($expireSeconds) {
            $post['expire_seconds'] = $expireSeconds;
        }

        return $this->request('qrcode/create', null, $post);
    }

    /**
     * 二维码下载地址
     * @see http://mp.weixin.qq.com/wiki/18/28fc21e7ed87bec960651f0ce873ef8a.html
     * @param string $ticket
     * @return string
     */
    public function url($ticket)
    {
        return 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . urlencode($ticket);
    }
}
